﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using Frogism.Core;
using Frogism.Data;

namespace Frogism.Domain {
  public class CategoryManager {
    public Collection<Category> GetCategories() {
      Collection<IObjectNameBase> basics = GetCategoriesBasic();
      Collection<Category> categories = new Collection<Category>();
      IEnumerable<ITransaction> trans = (new TransactionManager()).GetAll();
      IEnumerable<ITransaction> transUsed =
        trans.Where(t => t.TransactionType.Value == DBConst.TransactionTypeBill
          || t.TransactionType.Value == DBConst.TransactionTypeExpense
          || t.TransactionType.Value == DBConst.TransactionTypeInterest);

      foreach(IObjectNameBase c in basics) {
        categories.Add(Fill(c, transUsed));
      }
      Category total = new Category();
      total.Id = 999;
      total.Name = "Total";
      total.Month = categories.Sum(c => c.Month);
      total.LastMonth = categories.Sum(c => c.LastMonth);
      total.Year = categories.Sum(c => c.Year);
      total.Budget = categories.Sum(c => c.Budget);

      categories.Add(total);

      return categories;
    }
    public Collection<IObjectNameBase> GetCategoriesBasic() {
      ObjectNameBaseLoader loader = new ObjectNameBaseLoader();
      Collection<IObjectNameBase> categories = loader.GetAll("Category");
      //categories.Add(CategoryNullObject);
      return categories;
    }
    private static IObjectNameBase _CategoryNullObject;
    private IObjectNameBase CategoryNullObject {
      get {
        if(_CategoryNullObject == null) {
          _CategoryNullObject = new ObjectNameBase() { Id = 0, Name = "n/a" };
        }
        return _CategoryNullObject;
      }
    }
    public Category Fill(IObjectNameBase basic, IEnumerable<ITransaction> trans) {

      Category c = new Category();
      c.Id = basic.Id;
      c.Name = basic.Name;
      IEnumerable<ITransaction> cTrans = FilterTrans(trans, basic.Id);
      int thisMonth = DateTime.Now.Month;
      int thisYear = DateTime.Now.Year;
      int lastMonth = DateTime.Now.AddMonths(-1).Month;
      int lastYear = DateTime.Now.AddMonths(-1).Year;
      c.Month = cTrans.Where(t => t.TransactionDate.Month == thisMonth && t.TransactionDate.Year == thisYear).Sum(t => t.Amount);
      c.LastMonth = cTrans.Where(t => t.TransactionDate.Month == lastMonth && t.TransactionDate.Year == lastYear).Sum(t => t.Amount);
      c.Year = cTrans.Where(t => t.TransactionDate.Year ==thisYear).Sum(t => t.Amount);


      return c;
    }
    public IEnumerable<ITransaction> FilterTrans(IEnumerable<ITransaction> trans, int categoryId) {
      return trans.Where(t => (t.Category ?? CategoryNullObject).Id == categoryId);
      ;
    }
  }
}
